import React, { useRef, useEffect } from 'react';
import { Robot } from './types';
import { 
  ROBOT_SIZE, 
  ROBOT_SPEED, 
  ROBOT_INTERACTION_RADIUS, 
  MAX_ROBOT_MOVEMENT,
  THOUGHT_BUBBLE 
} from './constants';
import { isPointInFormArea } from './utils';

interface RobotAnimationProps {
  ctx: CanvasRenderingContext2D;
  canvas: HTMLCanvasElement;
  formPositionRef: React.MutableRefObject<{x: number, y: number, width: number, height: number}>;
  lowPerformanceMode: boolean;
}

// 绘制机器人
export const drawRobot = (
  ctx: CanvasRenderingContext2D, 
  robot: Robot, 
  lowPerformanceMode: boolean
): void => {
  // 使机器人更加明显 - 添加外发光
  ctx.beginPath();
  ctx.arc(robot.x, robot.y, robot.size * 1.2, 0, Math.PI * 2);
  const robotGlow = ctx.createRadialGradient(
    robot.x, robot.y, robot.size * 0.8,
    robot.x, robot.y, robot.size * 1.2
  );
  robotGlow.addColorStop(0, 'rgba(79, 70, 229, 0.0)');
  robotGlow.addColorStop(1, 'rgba(79, 70, 229, 0.3)'); // 增强发光效果
  ctx.fillStyle = robotGlow;
  ctx.fill();
  
  // 机器人身体（简化为圆形）- 增加高亮效果
  ctx.beginPath();
  ctx.arc(robot.x, robot.y, robot.size, 0, Math.PI * 2);
  
  // 使用渐变增加立体感
  const bodyGradient = ctx.createRadialGradient(
    robot.x - robot.size * 0.3, robot.y - robot.size * 0.3, 0,
    robot.x, robot.y, robot.size
  );
  bodyGradient.addColorStop(0, 'rgba(120, 122, 255, 0.95)');  // 提高亮部亮度
  bodyGradient.addColorStop(1, 'rgba(79, 70, 229, 0.9)');     // 提高暗部亮度
  
  ctx.fillStyle = bodyGradient;
  ctx.fill();
  
  // 添加外边框使机器人更加明显
  ctx.beginPath();
  ctx.arc(robot.x, robot.y, robot.size, 0, Math.PI * 2);
  ctx.strokeStyle = 'rgba(150, 150, 255, 0.8)';
  ctx.lineWidth = 1.5;
  ctx.stroke();
  
  // 机器人眼睛 - 增加更多细节，使其更自然可爱
  const eyeSize = robot.size * 0.3;
  const eyeDistance = robot.size * 0.4;
  
  // 计算眼睛的动画效果 - 眨眼
  const now = Date.now();
  const time = now * 0.001; // 当前时间(秒)
  
  // 更加自然的眨眼逻辑
  // 初始化眨眼状态
  if (!robot.lastBlinkTime) {
    robot.lastBlinkTime = now;
  }
  
  // 左右眼睛的缩放系数
  let leftEyeScaleY = 1;
  let rightEyeScaleY = 1;
  
  // 随机决定是双眼眨眼还是单眼眨眼
  const timeSinceLastBlink = now - robot.lastBlinkTime;
  const shouldBlink = timeSinceLastBlink > 2000 + Math.random() * 3000; // 2-5秒随机间隔
  
  if (shouldBlink) {
    robot.lastBlinkTime = now;
    
    // 随机决定眨眼模式：0=双眼, 1=左眼, 2=右眼
    const blinkMode = Math.floor(Math.random() * 5); // 80%概率双眼眨，20%概率单眼眨
    
    if (!robot.eyeState) {
      robot.eyeState = {
        left: { open: true, blinkProgress: 0 },
        right: { open: true, blinkProgress: 0 }
      };
    }
    
    if (blinkMode >= 0 && blinkMode <= 3) { // 双眼眨眼 (80%概率)
      robot.eyeState.left.open = false;
      robot.eyeState.left.blinkProgress = 0;
      robot.eyeState.right.open = false;
      robot.eyeState.right.blinkProgress = 0;
    } else if (blinkMode === 4) { // 单眼眨眼 (20%概率)
      if (Math.random() > 0.5) {
        robot.eyeState.left.open = false;
        robot.eyeState.left.blinkProgress = 0;
      } else {
        robot.eyeState.right.open = false;
        robot.eyeState.right.blinkProgress = 0;
      }
    }
  }
  
  // 更新眨眼进度
  if (robot.eyeState) {
    // 左眼
    if (!robot.eyeState.left.open) {
      robot.eyeState.left.blinkProgress += 0.15; // 眨眼动画速度
      
      if (robot.eyeState.left.blinkProgress < 0.3) {
        // 闭合阶段 - 使用平滑的缓动函数
        leftEyeScaleY = 1 - easeInOut(robot.eyeState.left.blinkProgress / 0.3) * 0.9;
      } else if (robot.eyeState.left.blinkProgress < 0.7) {
        // 保持闭合状态
        leftEyeScaleY = 0.1;
      } else if (robot.eyeState.left.blinkProgress < 1) {
        // 睁开阶段 - 使用平滑的缓动函数
        const openProgress = (robot.eyeState.left.blinkProgress - 0.7) / 0.3;
        leftEyeScaleY = 0.1 + easeInOut(openProgress) * 0.9;
      } else {
        // 眨眼动画完成
        robot.eyeState.left.open = true;
        leftEyeScaleY = 1;
      }
    }
    
    // 右眼
    if (!robot.eyeState.right.open) {
      robot.eyeState.right.blinkProgress += 0.15; // 眨眼动画速度
      
      if (robot.eyeState.right.blinkProgress < 0.3) {
        // 闭合阶段 - 使用平滑的缓动函数
        rightEyeScaleY = 1 - easeInOut(robot.eyeState.right.blinkProgress / 0.3) * 0.9;
      } else if (robot.eyeState.right.blinkProgress < 0.7) {
        // 保持闭合状态
        rightEyeScaleY = 0.1;
      } else if (robot.eyeState.right.blinkProgress < 1) {
        // 睁开阶段 - 使用平滑的缓动函数
        const openProgress = (robot.eyeState.right.blinkProgress - 0.7) / 0.3;
        rightEyeScaleY = 0.1 + easeInOut(openProgress) * 0.9;
      } else {
        // 眨眼动画完成
        robot.eyeState.right.open = true;
        rightEyeScaleY = 1;
      }
    }
  }
  
  // 定义缓动函数使过渡更自然
  function easeInOut(t: number): number {
    return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; // 三次方缓动函数
  }
  
  // 左眼眼眶
  ctx.beginPath();
  ctx.ellipse(
    robot.x - eyeDistance, 
    robot.y - eyeDistance * 0.5, 
    eyeSize, 
    eyeSize * leftEyeScaleY, 
    0, 0, Math.PI * 2
  );
  ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
  ctx.fill();
  
  // 右眼眼眶
  ctx.beginPath();
  ctx.ellipse(
    robot.x + eyeDistance, 
    robot.y - eyeDistance * 0.5, 
    eyeSize, 
    eyeSize * rightEyeScaleY, 
    0, 0, Math.PI * 2
  );
  ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
  ctx.fill();
  
  // 只在眼睛睁开足够时绘制眼球和反光点
  // 左眼球和反光
  if (leftEyeScaleY > 0.4) {
    // 计算眼球可见度基于当前眼睛高度
    const eyeballOpacity = (leftEyeScaleY - 0.4) / 0.6;
    
    // 眼球轻微移动效果
    const eyeOffsetX = Math.sin(time * 0.5) * eyeSize * 0.2;
    const eyeOffsetY = Math.cos(time * 0.7) * eyeSize * 0.1;
    
    // 左眼球
    ctx.beginPath();
    ctx.arc(
      robot.x - eyeDistance + eyeOffsetX, 
      robot.y - eyeDistance * 0.5 + eyeOffsetY, 
      eyeSize * 0.5 * leftEyeScaleY, // 眼球尺寸也随眼睛高度调整
      0, Math.PI * 2
    );
    ctx.fillStyle = `rgba(0, 0, 0, ${0.9 * eyeballOpacity})`;
    ctx.fill();
    
    // 左眼反光点 - 仅在眼睛大部分睁开时
    if (leftEyeScaleY > 0.7) {
      const reflectionOpacity = (leftEyeScaleY - 0.7) / 0.3;
      
      ctx.beginPath();
      ctx.arc(
        robot.x - eyeDistance + eyeOffsetX + eyeSize * 0.15, 
        robot.y - eyeDistance * 0.5 + eyeOffsetY - eyeSize * 0.15 * leftEyeScaleY, 
        eyeSize * 0.2 * leftEyeScaleY,
        0, Math.PI * 2
      );
      ctx.fillStyle = `rgba(255, 255, 255, ${0.95 * reflectionOpacity})`;
      ctx.fill();
    }
  }
  
  // 右眼球和反光
  if (rightEyeScaleY > 0.4) {
    // 计算眼球可见度基于当前眼睛高度
    const eyeballOpacity = (rightEyeScaleY - 0.4) / 0.6;
    
    // 眼球轻微移动效果
    const eyeOffsetX = Math.sin(time * 0.5) * eyeSize * 0.2;
    const eyeOffsetY = Math.cos(time * 0.7) * eyeSize * 0.1;
    
    // 右眼球
    ctx.beginPath();
    ctx.arc(
      robot.x + eyeDistance + eyeOffsetX, 
      robot.y - eyeDistance * 0.5 + eyeOffsetY, 
      eyeSize * 0.5 * rightEyeScaleY, // 眼球尺寸也随眼睛高度调整
      0, Math.PI * 2
    );
    ctx.fillStyle = `rgba(0, 0, 0, ${0.9 * eyeballOpacity})`;
    ctx.fill();
    
    // 右眼反光点 - 仅在眼睛大部分睁开时
    if (rightEyeScaleY > 0.7) {
      const reflectionOpacity = (rightEyeScaleY - 0.7) / 0.3;
      
      ctx.beginPath();
      ctx.arc(
        robot.x + eyeDistance + eyeOffsetX + eyeSize * 0.15, 
        robot.y - eyeDistance * 0.5 + eyeOffsetY - eyeSize * 0.15 * rightEyeScaleY, 
        eyeSize * 0.2 * rightEyeScaleY,
        0, Math.PI * 2
      );
      ctx.fillStyle = `rgba(255, 255, 255, ${0.95 * reflectionOpacity})`;
      ctx.fill();
    }
  }
  
  // 微笑表情 - 随时间略微变化，更自然
  const smileScale = 0.9 + Math.sin(time * 1.5) * 0.1; // 0.8-1.0之间变化
  ctx.beginPath();
  ctx.arc(
    robot.x, 
    robot.y + robot.size * 0.2, 
    robot.size * 0.2 * smileScale, 
    0, Math.PI, false
  );
  ctx.strokeStyle = 'rgba(0, 0, 0, 0.9)';
  ctx.lineWidth = 2;
  ctx.stroke();
  
  // 绘制思考泡泡 (只在思考状态下)
  if (robot.isThinking && !lowPerformanceMode && robot.thoughtBubbles && robot.thoughtBubbles.length > 0) {
    // 主思考泡泡
    const mainBubble = robot.thoughtBubbles[0];
    ctx.beginPath();
    ctx.arc(robot.x, robot.y - robot.size - THOUGHT_BUBBLE.TOP_MARGIN, mainBubble.size, 0, Math.PI * 2);
    ctx.fillStyle = `rgba(255, 255, 255, ${mainBubble.opacity})`;
    ctx.fill();
    
    // 添加小泡泡
    for (let i = 1; i < Math.min(4, robot.thoughtBubbles.length); i++) {
      const bubble = robot.thoughtBubbles[i];
      const angle = Math.PI * 1.25 + (i-1) * 0.2;
      const bubbleX = robot.x + Math.cos(angle) * (robot.size + bubble.size * 2);
      const bubbleY = robot.y + Math.sin(angle) * (robot.size + bubble.size * 2) - 5;
      
      ctx.beginPath();
      ctx.arc(bubbleX, bubbleY, bubble.size, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(255, 255, 255, ${bubble.opacity})`;
      ctx.fill();
    }
    
    // 如果在观察合并，添加感叹号或问号
    if (robot.observingMerge && robot.thoughtBubbles[0]) {
      const bubbleSize = robot.thoughtBubbles[0].size;
      ctx.font = `${bubbleSize * THOUGHT_BUBBLE.TEXT_SIZE_RATIO}px Arial`;
      ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('?!', robot.x, robot.y - robot.size - THOUGHT_BUBBLE.TOP_MARGIN);
    }
  }
  
  // 绘制机器人光环（当观察合并时）
  if (robot.observingMerge) {
    ctx.beginPath();
    ctx.arc(robot.x, robot.y, robot.size * 1.4, 0, Math.PI * 2);
    ctx.strokeStyle = 'rgba(79, 70, 229, 0.3)';
    ctx.lineWidth = 2;
    ctx.stroke();
  }
};

// 更新机器人
export const updateRobot = (
  robot: Robot,
  canvas: HTMLCanvasElement,
  formPositionRef: React.MutableRefObject<{x: number, y: number, width: number, height: number}>
): void => {
  // 如果没有目标位置或者已经接近目标，生成一个新目标
  if (
    !robot.targetX ||
    !robot.targetY ||
    (Math.abs(robot.x - robot.targetX) < 5 && Math.abs(robot.y - robot.targetY) < 5) ||
    Math.random() < 0.005 // 偶尔随机改变方向
  ) {
    // 设置新的目标位置，限制最大移动距离
    let validTarget = false;
    let attempts = 0;
    let newTargetX = 0;
    let newTargetY = 0;
    
    // 尝试找到一个不在表单区域内的目标位置
    while (!validTarget && attempts < 10) {
      const angle = Math.random() * Math.PI * 2;
      const distance = Math.random() * MAX_ROBOT_MOVEMENT;
      
      newTargetX = Math.max(robot.size, Math.min(canvas.width - robot.size, 
        robot.x + Math.cos(angle) * distance));
      newTargetY = Math.max(robot.size, Math.min(canvas.height - robot.size, 
        robot.y + Math.sin(angle) * distance));
      
      // 检查新目标是否在表单区域内
      if (!isPointInFormArea(newTargetX, newTargetY, canvas, formPositionRef)) {
        validTarget = true;
      }
      
      attempts++;
    }
    
    // 如果找到了有效目标，则更新机器人目标位置
    if (validTarget) {
      robot.targetX = newTargetX;
      robot.targetY = newTargetY;
    } else {
      // 否则尝试向远离表单的方向移动
      const formCenterX = canvas.width * formPositionRef.current.x;
      const formCenterY = canvas.height * formPositionRef.current.y;
      const directionX = robot.x - formCenterX;
      const directionY = robot.y - formCenterY;
      const magnitude = Math.sqrt(directionX * directionX + directionY * directionY);
      
      robot.targetX = Math.max(robot.size, Math.min(canvas.width - robot.size, 
        robot.x + (directionX / magnitude) * 100));
      robot.targetY = Math.max(robot.size, Math.min(canvas.height - robot.size, 
        robot.y + (directionY / magnitude) * 100));
    }
  }

  // 平滑移动到目标位置
  robot.x += (robot.targetX - robot.x) * 0.01 * robot.speed;
  robot.y += (robot.targetY - robot.y) * 0.01 * robot.speed;
  
  // 确保机器人不会进入表单区域
  if (isPointInFormArea(robot.x, robot.y, canvas, formPositionRef)) {
    const formCenterX = canvas.width * formPositionRef.current.x;
    const formCenterY = canvas.height * formPositionRef.current.y;
    const directionX = robot.x - formCenterX;
    const directionY = robot.y - formCenterY;
    const magnitude = Math.sqrt(directionX * directionX + directionY * directionY);
    
    // 向远离表单的方向移动
    robot.x += (directionX / magnitude) * robot.speed * 2;
    robot.y += (directionY / magnitude) * robot.speed * 2;
  }

  // 更新思考泡泡 - 简化为随机思考
  const now = Date.now();
  
  // 初始化lastThoughtTime（如果不存在）
  if (!robot.lastThoughtTime) {
    robot.lastThoughtTime = now;
  }
  
  // 随机产生思考状态
  if (!robot.isThinking && Math.random() < 0.01) {
    robot.isThinking = true;
    
    // 初始化思考泡泡
    robot.thoughtBubbles = [
      { x: robot.x, y: robot.y - robot.size - THOUGHT_BUBBLE.TOP_MARGIN, size: 0, opacity: THOUGHT_BUBBLE.OPACITY },
      { x: robot.x, y: robot.y - robot.size - THOUGHT_BUBBLE.TOP_MARGIN, size: 0, opacity: THOUGHT_BUBBLE.OPACITY },
      { x: robot.x, y: robot.y - robot.size - THOUGHT_BUBBLE.TOP_MARGIN, size: 0, opacity: THOUGHT_BUBBLE.OPACITY },
      { x: robot.x, y: robot.y - robot.size - THOUGHT_BUBBLE.TOP_MARGIN, size: 0, opacity: THOUGHT_BUBBLE.OPACITY }
    ];
    
    robot.lastThoughtTime = now;
  }
  
  // 更新思考泡泡
  if (robot.isThinking && robot.thoughtBubbles) {
    let allBubblesReachedMax = true;
    
    // 更新主泡泡和小泡泡
    for (let i = 0; i < robot.thoughtBubbles.length; i++) {
      const bubble = robot.thoughtBubbles[i];
      const maxSize = i === 0 ? THOUGHT_BUBBLE.MAIN_SIZE : THOUGHT_BUBBLE.SMALL_SIZE;
      
      if (bubble.size < maxSize) {
        bubble.size += THOUGHT_BUBBLE.GROW_SPEED;
        bubble.opacity = Math.min(THOUGHT_BUBBLE.OPACITY, bubble.size / maxSize * THOUGHT_BUBBLE.OPACITY);
        allBubblesReachedMax = false;
      }
    }
    
    // 如果所有泡泡都达到最大尺寸，有小概率停止思考
    if (allBubblesReachedMax && now - robot.lastThoughtTime > 3000 && Math.random() < 0.01) {
      robot.isThinking = false;
      robot.thoughtBubbles = [];
    }
  }
};

// 修改钩子函数，接收机器人尺寸参数
export default function useRobotAnimation(customRobotSize?: number) {
  const robotSize = customRobotSize || ROBOT_SIZE;
  
  const robotRef = useRef<Robot>({
    x: 0,
    y: 0,
    size: robotSize, // 使用自定义或默认尺寸
    speed: ROBOT_SPEED,
    isThinking: false,
    thoughtBubbles: [],
    lastThoughtTime: Date.now(),
    targetX: 0,
    targetY: 0,
    observingMerge: false,
    pauseMovement: 0,
    eyeState: {
      left: {
        open: true,
        blinkProgress: 0
      },
      right: {
        open: true,
        blinkProgress: 0
      }
    },
    lastBlinkTime: Date.now()
  });

  return {
    robotRef,
    updateRobot,
    drawRobot
  };
} 